<?php


namespace app\admin\controller;


use app\common\model\CardLevel;
use app\common\model\Category;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsList;
use app\common\model\OrderList;
use app\common\model\Shang;
use think\facade\Db;
use think\facade\View;
use think\Request;

class CardGoods extends Base
{
    /**
     * 分类列表
     * @param Request $request
     * @return string
     *created by Admin at 2022/12/6 9:27
     */
    public function category(Request $request)
    {
        //获取分类数据
        $data = Category::getList([], '*', "id asc", 100);
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("CardGoods/card_goods_category");
    }

    /**
     * @param Request $request
     * @return string|\think\response\Json
     *created by Admin at 2022/12/6 9:27
     * 分类添加
     */
    public function card_category_add(Request $request)
    {
        if (!$request->isPost()) {
            return View::fetch("CardGoods/card_category_add");
        } else {
            $data = input('post.');
            if (empty($data['title'])) {
                return $this->renderError("请输入分类名称");
            }
            if (RegZero($data['sort'])) {
                return $this->renderError("排序输入不规范,请输入整数");
            }
            $data['addtime'] = time();
            $res = Category::insert($data);
            if ($res) {
                return $this->renderSuccess("添加成功");
            } else {
                return $this->renderError("网络繁忙，请稍后");
            }
        }
    }

    /**
     * 分类编辑
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/6 9:50
     */
    public function card_category_edit(Request $request)
    {
        if (!$request->isPost()) {
            $id = $request->param('id/d', 0);
            $info = Category::where(['id' => $id])->find();
            if (empty($info)) {
                return $this->renderError("数据不存在");
            }
            $type = $info['type'];
            View::assign('type', $type);
            View::assign('info', $info);
            return View::fetch("CardGoods/card_category_edit");
        } else {
            $data = $request->post();
            if (empty($data['id'])) {
                return $this->renderError("请求参数错误");
            }
            $info = Category::where(['id' => $data['id']])->find();
            if (!$info) {
                return $this->renderError("数据不存在");
            }
            if (empty($data['title'])) {
                return $this->renderError("请输入分类名称");
            }
            if (RegZero($data['sort'])) {
                return $this->renderError("排序输入不规范,请输入整数");
            }
            $data['update_time'] = time();
            Db::startTrans();
            $res[] = $info->allowField([])->update($data);
            if (resCheck($res)) {
                Db::commit();
                return $this->renderSuccess("编辑成功");
            } else {
                Db::rollback();
                return $this->renderError("网络繁忙，请稍后");
            }

        }
    }

    /**
     * 分类删除
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/6 9:55
     */
    public function card_category_del(Request $request)
    {
        $id = $request->post('id/d');
        $data = Category::where(['id' => $id])->field('id')->find();
        if (!$data) {
            return $this->renderError("数据不存在");
        }
        $result = Category::where(['id' => $id])->delete();
        if ($result) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("删除失败，请稍后重试");
        }
    }

    /**
     * 抽卡机列表
     * @param Request $request
     *created by Admin at 2022/12/6 10:05
     */
    public function card_goods(Request $request){
        $title = trim(input('get.title'));
        $status = trim(input('get.status'));
        $where = array();
        $where[] = ['type', '=', 4];
        if (!empty($title)) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }
        if (!empty($status)) {
            $where[] = ['status', '=', $status];
        }
        //查询抽卡机数据
        $data = GoodsModel::getList($where, "*", "id desc", $this->page);
        foreach ($data['list'] as &$value) {
            $category_name = Category::field('title')->where('id', '=', $value['category_id'])->value('title');
            $value['category_name'] = $category_name;
            //盒子等级列表
            $all_sale_stock = 0;
            $all_special_stock = 0;
            $shang = CardLevel::field('id,title')->select();
            foreach ($shang as &$shang_value) {
//                #赏等级奖品
//                $goodslist_count = GoodsList::field('id')
//                    ->where('goods_id', '=', $value['id'])
//                    ->where('shang_id', '=', $shang_value['id'])
//                    ->count();
//                $shang_value['goodslist_count'] = $goodslist_count;
                #库存
                $special_stock = GoodsList::field('special_stock')
                    ->where('goods_id', '=', $value['id'])
                    ->where('shang_id', '=', $shang_value['id'])
                    ->where('special_stock', '>', 0)
                    ->sum('special_stock');
                $shang_value['special_stock'] = $special_stock;
                $all_special_stock += $special_stock;
                #销量
                $sale_stock = OrderList::field('id')
                    ->where('goods_id', '=', $value['id'])
                    ->where('shang_id', '=', $shang_value['id'])
                    ->count();
                $shang_value['sale_stock'] = $sale_stock;
                $all_sale_stock += $sale_stock;
            }
            $value['shang'] = $shang;
            $value['all_sale_stock'] = $all_sale_stock;
            $value['all_special_stock'] = $all_special_stock;
        }
        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        return View::fetch("CardGoods/card_goods");
    }

    /**
     * 添加盒子
     * @param Request $request
     *created by Admin at 2022/12/6 14:26
     */
    public function card_goods_add(Request $request){
        if (!$request->isPost()) {

            $category = Category::field('id,title')->select();
            View::assign('category', $category);
            return View::fetch("CardGoods/card_goods_add");
        }else{
            $data = $request->post();
            if (empty($data['title'])) {
                return $this->renderError("请输入盒子名称");
            }
            if (RegMoney($data['price'])) {
                return $this->renderError("盒子价格输入不规范,最多保留两位小数");
            }
            if (RegZero($data['sort'])) {
                return $this->renderError("排序输入不规范,请输入整数");
            }
            if (RegZero($data['card_num'])) {
                return $this->renderError("张数输入不规范,请输入整数");
            }
            if (empty($data['category_id'])) {
                return $this->renderError("请选择分类");
            }
            if (empty($data['category_id'])) {
                return $this->renderError("请选择分类");
            }
            if ($data['coupon_is'] == 1) {
                if (RegInt($data['coupon_pro'])) {
                    return $this->renderError("发券概率请设置大于0的整数");
                }
            } elseif ($data['coupon_is'] == 0) {
                $data['coupon_pro'] = 0;
            } else {
                return $this->renderError("发券开关选择错误");
            }
            if ($data['integral_is'] != 0 && $data['integral_is'] != 1) {
                return $this->renderError("发积分开关选择错误");
            }
            if (empty($data['imgurl'])) {
                return $this->renderError("请上传盒子封面图");
            }
            if (empty($data['imgurl_detail'])) {
                return $this->renderError("请上传盒子详情封面图");
            }
            if (empty($data['prize_imgurl'])) {
                return $this->renderError("请上传卡牌背面图");
            }
            if (empty($data['card_banner'])) {
                return $this->renderError("请上传卡册banner");
            }
            $data['type'] = 4;
            $data['status'] = 2;
            $data['addtime'] = time();
            $card_set = getConfig('card_set');
            unset($card_set['update_time']);
            $data['card_set'] = json_encode($card_set);
            $dd = GoodsModel::insert($data);
            if ($dd) {
                return $this->renderSuccess("添加成功");
            } else {
                return $this->renderError("网络繁忙，请稍后");
            }

        }
    }

    /**
     * 编辑盒子
     * @param Request $request
     *created by Admin at 2022/12/6 15:32
     */
    public function card_goods_edit(Request $request){
        if (!$request->isPost()) {
            $id = $request->param('id', 0);
            $info = GoodsModel::where(['id' => $id])->find();
            if (!$info) {
                return $this->renderError("请求参数错误");
            }
            $type = $info['type'];
            $category = Category::field('id,title')->select();
            View::assign('category', $category);
            View::assign('type', $type);
            View::assign('info', $info);
            return View::fetch("CardGoods/card_goods_edit");
        }else{
            $data = $request->post();
            if (empty($data['id'])) {
                return $this->renderError("请求参数错误");
            }
            $info = GoodsModel::where(['id' => $data['id']])->find();
            if (!$info) {
                return $this->renderError("盒子数据不存在");
            }
            if (empty($data['title'])) {
                return $this->renderError("请输入盒子名称");
            }
            if (RegMoney($data['price'])) {
                return $this->renderError("盒子价格输入不规范,最多保留两位小数");
            }
            if (RegZero($data['sort'])) {
                return $this->renderError("排序输入不规范,请输入整数");
            }
            if (RegZero($data['card_num'])) {
                return $this->renderError("张数输入不规范,请输入整数");
            }
            if (empty($data['category_id'])) {
                return $this->renderError("请选择分类");
            }
            if ($data['coupon_is'] == 1) {
                if (RegInt($data['coupon_pro'])) {
                    return $this->renderError("发券概率请设置大于0的整数");
                }
            } elseif ($data['coupon_is'] == 0) {
                $data['coupon_pro'] = 0;
            } else {
                return $this->renderError("发券开关选择错误");
            }
            if ($data['integral_is'] != 0 && $data['integral_is'] != 1) {
                return $this->renderError("发积分开关选择错误");
            }
            if (empty($data['imgurl'])) {
                return $this->renderError("请上传盒子封面图");
            }
            if (empty($data['imgurl_detail'])) {
                return $this->renderError("请上传盒子封面图");
            }
            if (empty($data['prize_imgurl'])) {
                return $this->renderError("请上传卡牌背面图");
            }
            if (empty($data['card_banner'])) {
                return $this->renderError("请上传卡册banner");
            }
            $data['update_time'] = time();
            Db::startTrans();
            $res = [];
            $res[] = $info->allowField([])->update($data);
            if (resCheck($res)) {
                Db::commit();
                return $this->renderSuccess("编辑成功");
            } else {
                Db::rollback();
                return $this->renderError("网络繁忙，请稍后");
            }
        }
    }

    /**
     * 删除盒子
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/6 15:39
     */
    public function card_goods_del(Request $request)
    {
        $id = $request->post('id/d');
        $status = $request->post('type/d');
        $data = GoodsModel::where(['id' => $id])->field('id')->find();
        if (!$data) {
            return $this->renderError("数据不存在");
        }
        if ($status == 1 || $status == 2) {
            $result = GoodsModel::where(['id' => $id])->update(['status' => $status]);
        } elseif ($status == 3) {
            $result = GoodsModel::where(['id' => $id])->update(['delete_time' => time(), 'status' => 2]);
        } else {
            return $this->renderError("请求参数错误");
        }
        if ($result) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("网络繁忙，请稍后");
        }
    }

    /**
     * 商品列表
     * @param Request $request
     *created by Admin at 2022/12/6 15:53
     */
    public function shang_goods(Request $request){
//        dd(11);
        $card_id = $request->param('card_id/d',0);
        $title = trim(input('get.title'));
        $whe = array();
        $whe[] = ['goods_id', '=', $card_id];

        $whe[] = ['num', '=', 0];
        if (!empty($title)) {
            $whe[] = ['title', 'like', '%' . $title . '%'];
        }
        $field = "*";
        $order = "sort desc,shang_id asc,id asc";
        $data = GoodsList::getList($whe, $field, $order, 150);
        $real_pro = 0;
        foreach ($data['list'] as &$value) {

            $shang_title = CardLevel::where(['id' => $value['shang_id']])->value('title');
            if ($shang_title){
                $value['shang'] = $shang_title;
            }else{
                $value['shang'] = '无';
            }
            if ($value['goods_type'] == 2) {
                $value['sale_time'] = date('Y-m-d', $value['sale_time']);
            } else {
                $value['sale_time'] = '';
            }
            $real_pro += $value['real_pro'];
        }

        View::assign('list', $data['list']);
        View::assign('count', $data['count']);
        View::assign('page', $data['page']);
        View::assign('real_pro', $real_pro);
        View::assign('card_id', $card_id);
        return View::fetch("CardGoods/shang_goods");
    }

    /**
     * 添加商品
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/6 16:19
     */
    public function shang_goods_add(Request $request)
    {
        if (!$request->isPost()) {
            $card_id = $request->param('card_id/d', 0);
            $info = GoodsModel::where(['id' => $card_id])->find();
            if (!$info) {
                return $this->renderError("请求参数错误");
            }
            #卡牌赏等级
            $shang = CardLevel::field('id,title')
                ->order('sort desc,id asc')
                ->select()->toArray();
            View::assign('info', $info);
            View::assign('shang', $shang);
            return View::fetch('CardGoods/shang_goods_add');
        } else {
            $data = $request->post();

            if (empty($data['shang_id'])) {
                return $this->renderError('请求参数错误');
            }

            $goods = GoodsModel::where(['id' => $data['card_id']])->find();
            if (!$goods) {
                return $this->renderError('数据不存在');
            }
            if (empty($data['title'])) {
                return $this->renderError('请输入卡名称');
            }
            if (empty($data['shang_id'])) {
                return $this->renderError('请选择卡等级');
            }
            if (RegMoney($data['price'])) {
                return $this->renderError('奖品售价设置错误,最多保留两位小数');
            }
            if (RegMoney($data['money'])) {
                return $this->renderError('兑换价格设置错误,最多保留两位小数');
            }
            if ($data['goods_type'] == 1) {
                $data['sale_time'] = 0;
            } else if ($data['goods_type'] == 2) {
                if (empty($data['sale_time'])) {
                    return $this->renderError('请选择预售时间');
                }
                $today_time = strtotime(date('Y-m-d', time()));
                $data['sale_time'] = strtotime($data['sale_time']);
                if ($today_time >= $data['sale_time']) {
                    return $this->renderError('预售时间请在今天之后');
                }
            } else {
                return $this->err('奖品类型选择错误');
            }
            if ($data['special_stock'] != -100) {
                if (RegZero($data['special_stock'])) {
                    return $this->renderError('奖品数量设置错误,请设置整数');
                }
            }
            if (RegMoney($data['real_pro'])) {
                return $this->renderError('等级内概率设置错误,最多保留两位小数');
            }
            if (RegZero($data['sort'])) {
                return $this->renderError('排序请输入整数');
            }
            if (empty($data['imgurl'])) {
                return $this->renderError('请上传图片');
            }
            $data['addtime'] = time();
            $data['prize_code'] = getPrizeCode() . '_' . time();
            $data['goods_id'] = $data['card_id'];
            unset($data['card_id']);
            $res = GoodsList::insert($data);
            if ($res) {
                return $this->renderSuccess('添加成功');
            } else {
                return $this->renderError('添加失败');
            }
        }
    }

    /**
     * 编辑商品
     * @param Request $request
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *created by Admin at 2022/12/7 8:48
     */
    public function shang_goods_edit(Request $request){
        if (!$request->isPost()) {
            $id = $request->param('id/d', 0);
            $goods = GoodsList::where(['id' => $id])->find();
            if (!$goods) {
                return $this->renderError('请求参数错误');
            }
            if ($goods['goods_type'] == 2) {
                $goods['sale_time'] = date('Y-m-d', $goods['sale_time']);
            } else {
                $goods['sale_time'] = '';
            }
            $info = GoodsModel::where(['id' => $goods['goods_id']])->find();
            if (!$info) {
                return $this->renderError('请求参数错误1');
            }
            $card_list = GoodsModel::where('id', '=', $goods['goods_id'])->find();
            if (!$card_list) {
                return $this->renderError('请求参数错误2');
            }
            #卡牌赏等级
            $shang = CardLevel::field('id,title')
                ->order('sort desc,id asc')
                ->select()->toArray();
            View::assign('goods', $goods);
            View::assign('shang_title', $card_list['title']);
            View::assign('shang', $shang);
            return View::fetch('CardGoods/shang_goods_edit');
        } else {
            $data = $request->post();

            if (empty($data['id'])) {
                return $this->renderError('参数错误');
            }
            $goods = GoodsList::where(['id' => $data['id']])->find();
            if (!$goods) {
                return $this->renderError('参数错误');
            }
            $info = GoodsModel::where(['id' => $goods['goods_id']])->find();
            if (!$info) {
                return $this->renderError('参数错误');
            }
            $shang = CardLevel::where('id', '=', $data['shang_id'])->find();
            if (!$shang) {
                return $this->renderError('参数错误');
            }
            if (empty($data['title'])) {
                return $this->renderError('请输入奖品名称');
            }
            if (RegMoney($data['price'])) {
                return $this->renderError('奖品售价设置错误,最多保留两位小数');
            }
            if (RegMoney($data['money'])) {
                return $this->renderError('兑换价格设置错误,最多保留两位小数');
            }
            if ($data['goods_type'] == 1) {
                $data['sale_time'] = 0;
            } else if ($data['goods_type'] == 2) {
                if (empty($data['sale_time'])) {
                    return $this->renderError('请选择预售时间');
                }
                $today_time = strtotime(date('Y - m - d', time()));
                $data['sale_time'] = strtotime($data['sale_time']);
                if ($today_time >= $data['sale_time']) {
                    return $this->renderError('预售时间请在今天之后');
                }
            } else {
                return $this->err('奖品类型选择错误');
            }
            if ($data['special_stock'] != -100) {
                if (RegZero($data['special_stock'])) {
                    return $this->renderError('奖品数量设置错误,请设置整数');
                }
            }
            if (RegMoney($data['real_pro'])) {
                return $this->renderError('等级内概率设置错误,最多保留两位小数');
            }
            if (RegZero($data['sort'])) {
                return $this->renderError('排序请输入整数');
            }
            if (empty($data['imgurl'])) {
                return $this->renderError('请上传图片');
            }
            $data['update_time'] = time();
            unset($data['id']);
            $res = GoodsList::where(['prize_code' => $goods['prize_code']])->update($data);
            if ($res) {
                return $this->renderSuccess('编辑成功');
            } else {
                return $this->renderError('编辑失败');
            }
        }
    }

    /**
     * 删除商品
     * @param Request $request
     * @return \think\response\Json
     *created by Admin at 2022/12/7 8:53
     */
    public function shang_goods_del(Request $request)
    {
        $id = $request->param('id/d', 0);
        $prize_code = GoodsList::field('prize_code')
            ->where(['id' => $id])
            ->value('prize_code');
        if (!$prize_code) {
            return $this->renderError("请勿重复操作");
        }
        #删除奖品
        $res = GoodsList::field('id')
            ->where(['prize_code' => $prize_code])
            ->delete();
        if ($res) {
            return $this->renderSuccess("操作成功");
        } else {
            return $this->renderError("操作失败");
        }
    }

    /**
     * 卡设置
     * @return string|\think\response\Json
     *created by Admin at 2022/12/7 9:05
     */
    public function card_set()
    {
        if (request()->isGet()) {
            $info = getConfig('card_set');

            #卡牌赏等级
            $shang = CardLevel::field('id,title')
                ->order('sort desc,id asc')
                ->select()->toArray();
            View::assign("shang", $shang);
            View::assign("info", $info);
            return View::fetch('CardGoods/card_set');
        } else {
            $data = input("post.");
            $data['update_time'] = time();
            $result = setConfig('card_set', $data);
            if ($result) {
                return $this->renderSuccess('修改成功');
            } else {
                return $this->renderError('修改失败');
            }
        }

    }

}